Popular Searches
Popular Course Categories
Popular Courses

Integrating File System and Document Handling

Integrating File System and Document Handling

Device Features and Native Capabilities

Integrating File System and Document Handling in React Native

Course: React Native Training

Topic: Integrating File System and Document Handling

Course Link: React Native Training Course

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to File System and Document Handling

File system and document handling are important features in React Native applications. They allow applications to create, read, write, copy, move, download, upload, and delete files stored on a device or accessed through a document provider.

These capabilities are useful in applications that manage invoices, reports, receipts, PDFs, images, profile documents, exported data, downloaded resources, and user-generated content. For example, a finance application may let users download an invoice, save it locally, and share it with another application.

React Native applications can access files through platform APIs and libraries. In Expo projects, expo-file-system provides local file operations, while expo-document-picker opens the operating system's document selection interface. Other libraries may be appropriate when a project needs advanced document viewing, directory selection, or native file management.

Official documentation: Expo FileSystem Documentation and Expo DocumentPicker Documentation.

1.1 What Is a File System?

A file system organizes data into files and directories. In a mobile application, file operations are usually restricted to locations and resources permitted by the operating system. Applications may have their own private storage areas and can use system interfaces to access documents selected by the user.

1.2 What Is Document Handling?

Document handling refers to the process of selecting, importing, opening, reading, creating, saving, exporting, sharing, or uploading documents. Supported document formats depend on the application and the libraries it uses.

1.3 Common Use Cases

  • Selecting a PDF, text file, spreadsheet, or other document.
  • Downloading invoices, certificates, and reports.
  • Saving application-generated files for offline access.
  • Reading and writing JSON or text data.
  • Uploading documents to a backend server.
  • Exporting information from the application.
  • Sharing files with other applications.
  • Managing temporary files and cached downloads.

2. Learning Objectives

After completing this topic, learners should be able to:

  • Understand file system concepts in React Native.
  • Install and configure Expo FileSystem and DocumentPicker.
  • Understand local file URIs and directory paths.
  • Select documents using the system document picker.
  • Create, read, write, copy, move, and delete files.
  • Download files from remote servers.
  • Upload files using multipart requests.
  • Manage temporary files and persistent application data.
  • Handle file permissions, errors, and unsupported formats.
  • Implement document validation and secure file handling.
  • Build a document management feature for a React Native application.

3. Setting Up the Development Environment

3.1 Create an Expo Project

If you do not already have a React Native project, create one using the following commands:

npx create-expo-app FileHandlingApp
cd FileHandlingApp
npx expo start

If you already have a compatible Expo project, you can install the required libraries directly.

3.2 Install Expo FileSystem

Run the following command to install the file system library compatible with your Expo SDK:

npx expo install expo-file-system

Expo FileSystem provides access to application files and directories, file reading and writing, file metadata, and supported download operations.

3.3 Install Expo DocumentPicker

npx expo install expo-document-picker

DocumentPicker opens the operating system's document selection interface. Users can select documents from available providers, such as local storage or cloud document services supported by the device.

3.4 Import the Libraries

import { File, Directory, Paths } from 'expo-file-system';
import * as DocumentPicker from 'expo-document-picker';

The current Expo FileSystem API includes object-oriented interfaces such as File, Directory, and Paths. Older examples may use legacy functions such as FileSystem.readAsStringAsync(). Use the API supported by the installed package version rather than mixing legacy and current APIs indiscriminately.

4. Understanding File System Storage Locations

Mobile applications can use different storage locations depending on whether a file is temporary, intended to persist, or selected from an external document provider.

Storage Location Purpose Typical Use
Cache directory Temporary files that may be removed by the operating system Previews, temporary downloads, processing files
Application document directory Files intended to remain available to the app Saved reports and offline documents
Temporary picker copy A copy of a user-selected document created for immediate access Reading or uploading a selected file
System document provider A document managed by the operating system or another provider Files selected from cloud storage or a document service
Remote server or cloud storage Files stored outside the device Shared documents and cross-device access

4.1 Accessing Common Directories

In the current Expo FileSystem API, the Paths object exposes commonly used application directories.

import { Paths } from 'expo-file-system';

console.log('Cache directory:', Paths.cache.uri);
console.log('Document directory:', Paths.document.uri);

The cache directory is appropriate for temporary files that can be recreated or downloaded again. The document directory is more suitable for application data that should remain available across normal app restarts. Neither should be treated as guaranteed permanent storage after app removal or device cleanup.

4.2 File URI Versus File Name

A filename such as invoice.pdf identifies a file by name. A URI such as file:///... identifies a location or resource that an application can attempt to access.

A document picker may return a URI that is not a simple local filesystem path. For example, Android can use content URIs, and iOS can provide document-provider URLs. Do not assume every URI can be manipulated as a normal file path.

5. Selecting Documents Using DocumentPicker

The document picker allows users to select a file using a system-provided interface. This is generally preferable to asking for broad filesystem access because the user chooses the specific document to share with the application.

5.1 Basic Document Selection

import * as DocumentPicker from 'expo-document-picker';

async function pickDocument() {
  try {
    const result = await DocumentPicker.getDocumentAsync({
      type: '*/*',
      multiple: false,
      copyToCacheDirectory: true,
    });

    if (result.canceled) {
      console.log('Document selection canceled');
      return null;
    }

    const document = result.assets[0];

    console.log('Name:', document.name);
    console.log('URI:', document.uri);
    console.log('Size:', document.size);
    console.log('MIME type:', document.mimeType);

    return document;
  } catch (error) {
    console.error('Document selection failed:', error);
    return null;
  }
}

5.2 Understanding the Options

Option Description
type Specifies accepted MIME types, such as application/pdf or image/*.
multiple Allows selection of multiple files when set to true.
copyToCacheDirectory Copies the selected document into the app's cache when supported, making immediate access through Expo FileSystem more reliable.
canceled Indicates whether the selection operation was canceled.
assets Contains the selected document information when selection succeeds.

5.3 Restricting the Accepted File Type

To select only PDF files, set the MIME type to application/pdf.

const result = await DocumentPicker.getDocumentAsync({
  type: 'application/pdf',
  multiple: false,
  copyToCacheDirectory: true,
});

For image documents, use image/*. To accept common text documents, provide an array of relevant MIME types supported by the picker. The system's available document providers and file associations may affect the results.

5.4 Selecting Multiple Documents

const result = await DocumentPicker.getDocumentAsync({
  type: '*/*',
  multiple: true,
  copyToCacheDirectory: true,
});

if (!result.canceled) {
  result.assets.forEach((asset) => {
    console.log(asset.name, asset.uri);
  });
}

When multiple selection is enabled, validate each file independently. Avoid assuming all selected documents have the same MIME type, size, or accessibility.

6. Understanding Document Metadata

The document picker returns information about each selected file. Some fields may not be available for every platform or document provider.

Property Purpose Example
name Selected file's name report.pdf
uri Reference to the selected file file:///.../report.pdf
size File size in bytes when available 1048576
mimeType Reported media type when available application/pdf
lastModified Modification timestamp when available Platform-dependent numeric timestamp

6.1 Safely Reading Metadata

function getDocumentDetails(document) {
  return {
    name: document.name || 'Unnamed document',
    uri: document.uri,
    size: document.size ?? null,
    mimeType: document.mimeType || 'Unknown type',
    lastModified: document.lastModified ?? null,
  };
}

Metadata is useful for display and basic validation, but it is not proof that a file is safe. For example, a filename ending in .pdf does not guarantee that its contents are a valid PDF.

7. Creating and Writing Files

Applications may need to create local files for notes, reports, exports, logs, or downloaded content. The current Expo FileSystem API uses a File object to represent a file.

7.1 Creating a Text File

import { File, Paths } from 'expo-file-system';

function createTextFile() {
  try {
    const file = new File(Paths.document, 'example.txt');

    file.create();
    file.write('Hello from React Native!');

    console.log('File created at:', file.uri);
    return file.uri;
  } catch (error) {
    console.error('Unable to create file:', error);
    return null;
  }
}

The example creates a file in the app's document directory and writes text into it. If the file already exists, creation may fail unless the appropriate overwrite or idempotent behavior is configured. Choose the correct options for the installed Expo SDK.

7.2 Writing to a File

import { File, Paths } from 'expo-file-system';

async function writeNotes() {
  const file = new File(Paths.document, 'notes.txt');

  try {
    if (!file.exists) {
      file.create();
    }

    await file.write('These are my application notes.');
    console.log('Notes saved successfully');
  } catch (error) {
    console.error('Unable to save notes:', error);
  }
}

Check the behavior of create() and write() in the installed version. Decide whether a write should replace existing content or append to it. For large files, prefer appropriate asynchronous or streaming operations where supported.

7.3 Writing JSON Data

JSON files are useful for storing structured information such as export data, non-sensitive preferences, or locally generated reports.

import { File, Paths } from 'expo-file-system';

async function saveJsonFile() {
  const data = {
    userId: 'user-123',
    theme: 'light',
    language: 'en',
  };

  const file = new File(Paths.document, 'settings-export.json');

  try {
    if (!file.exists) {
      file.create();
    }

    await file.write(JSON.stringify(data, null, 2));
    console.log('JSON file saved');
  } catch (error) {
    console.error('JSON save failed:', error);
  }
}

Do not use a plain JSON file in general document storage as a secure store for passwords, refresh tokens, or other secrets. Use platform-appropriate secure storage for sensitive credentials.

8. Reading File Contents

Reading a file allows an application to process its contents, display saved information, or prepare data for another operation.

8.1 Reading a Text File

import { File, Paths } from 'expo-file-system';

function readTextFile() {
  try {
    const file = new File(Paths.document, 'example.txt');

    if (!file.exists) {
      console.log('File does not exist');
      return null;
    }

    const content = file.textSync();
    console.log(content);

    return content;
  } catch (error) {
    console.error('Unable to read file:', error);
    return null;
  }
}

The current Expo FileSystem API includes synchronous and asynchronous reading methods. Synchronous operations can block the JavaScript thread, so use asynchronous operations for potentially large files or operations that may take noticeable time.

8.2 Reading JSON Data

import { File, Paths } from 'expo-file-system';

async function readJsonFile() {
  try {
    const file = new File(Paths.document, 'settings-export.json');

    if (!file.exists) {
      return null;
    }

    const content = await file.text();
    const data = JSON.parse(content);

    return data;
  } catch (error) {
    console.error('Unable to read JSON file:', error);
    return null;
  }
}

Parsing can fail if the file contains invalid JSON. Production code should handle malformed data and decide whether to restore a default value, report an error, or request a new copy.

9. Copying, Moving, and Deleting Files

File management includes organizing files, moving temporary content to persistent storage, and removing files that are no longer needed.

9.1 Copying a File

import { File, Paths } from 'expo-file-system';

function copyDocument() {
  try {
    const source = new File(Paths.document, 'example.txt');
    const destination = new File(Paths.document, 'example-copy.txt');

    if (!source.exists) {
      throw new Error('Source file does not exist');
    }

    source.copy(destination);
    console.log('File copied to:', destination.uri);
  } catch (error) {
    console.error('Copy failed:', error);
  }
}

Confirm the source and destination semantics for the installed SDK. Avoid copying a file onto itself or unintentionally overwriting an existing important document.

9.2 Moving a File

import { File, Paths } from 'expo-file-system';

function moveDocument() {
  try {
    const source = new File(Paths.cache, 'temporary.txt');
    const destination = new File(Paths.document, 'saved.txt');

    if (!source.exists) {
      throw new Error('Source file does not exist');
    }

    source.move(destination);
    console.log('File moved successfully');
  } catch (error) {
    console.error('Move failed:', error);
  }
}

Moving a file can change its location and affect any stored references. Update application state or database records when the path changes. If the source is a provider-managed URI rather than a normal local file, a copy or import workflow may be necessary instead.

9.3 Deleting a File

import { File, Paths } from 'expo-file-system';

function deleteDocument() {
  try {
    const file = new File(Paths.document, 'example-copy.txt');

    if (file.exists) {
      file.delete();
      console.log('File deleted');
    }
  } catch (error) {
    console.error('Deletion failed:', error);
  }
}

Before deleting a file, verify that it is the intended target. Avoid deleting files based on untrusted path input. If a document is referenced by a database or upload queue, update that state as part of the same workflow.

10. Working with Directories

Directories help organize files by category, feature, or lifecycle. For example, an application may keep downloaded reports in one directory and temporary processing files in another.

10.1 Creating a Directory

import { Directory, Paths } from 'expo-file-system';

function createReportsDirectory() {
  try {
    const directory = new Directory(Paths.document, 'reports');

    if (!directory.exists) {
      directory.create();
    }

    console.log('Reports directory:', directory.uri);
    return directory.uri;
  } catch (error) {
    console.error('Directory creation failed:', error);
    return null;
  }
}

10.2 Directory Organization Example

Application Storage/
  reports/
    monthly-report.pdf
    annual-report.pdf
  exports/
    transactions.json
  cache/
    preview.tmp

This is a conceptual structure. The actual directory layout should use paths and directory operations supported by the chosen platform and library.

10.3 Listing Directory Contents

In the current Expo FileSystem API, a directory can expose its child entries. Check that the directory exists before listing it.

import { Directory, Paths } from 'expo-file-system';

function listReports() {
  try {
    const directory = new Directory(Paths.document, 'reports');

    if (!directory.exists) {
      console.log('Reports directory does not exist');
      return [];
    }

    const entries = directory.list();

    entries.forEach((entry) => {
      console.log(entry.name, entry.uri);
    });

    return entries;
  } catch (error) {
    console.error('Unable to list reports:', error);
    return [];
  }
}

11. Downloading Files from a Server

Applications frequently need to download files such as invoices, certificates, reports, and user attachments. A download workflow should handle network failures, HTTP errors, file naming, storage location, and user feedback.

11.1 Downloading a File

The current Expo FileSystem API provides download functionality. The following example downloads a file to the app's document directory.

import { File, Paths } from 'expo-file-system';

async function downloadReport() {
  try {
    const url = 'https://example.com/sample-report.pdf';
    const destination = new File(Paths.document, 'sample-report.pdf');

    const downloadedFile = await File.downloadFileAsync(
      url,
      destination
    );

    console.log('Downloaded file:', downloadedFile.uri);
    return downloadedFile.uri;
  } catch (error) {
    console.error('Download failed:', error);
    return null;
  }
}

Replace the example URL with your actual file endpoint. Check the current FileSystem documentation for the exact download method signature and options supported by your installed Expo SDK.

11.2 Download Workflow

  1. The user chooses a document to download.
  2. The application validates the requested URL and expected file type.
  3. The download starts using the appropriate file system API.
  4. The application tracks progress if supported and required.
  5. The application checks whether the download completed successfully.
  6. The file is saved to an appropriate application directory.
  7. The UI displays a success message and provides an action to open or share the file.

11.3 Important Download Considerations

  • Handle slow connections and interrupted downloads.
  • Validate HTTP response status and the final downloaded file.
  • Use a sensible filename and avoid path traversal.
  • Consider file size limits before downloading large resources.
  • Use authenticated requests where the backend requires them.
  • Do not trust arbitrary URLs provided by users without validation.

12. Uploading Documents to a Backend

Uploading lets users submit documents to a backend for processing, storage, or sharing. A common approach is to send the selected file using a multipart HTTP request.

12.1 Uploading with FormData

async function uploadDocument(document, token) {
  if (!document?.uri) {
    throw new Error('No document selected');
  }

  const formData = new FormData();

  formData.append('file', {
    uri: document.uri,
    name: document.name || 'upload.bin',
    type: document.mimeType || 'application/octet-stream',
  });

  const response = await fetch('https://api.example.com/upload', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${token}`,
    },
    body: formData,
  });

  if (!response.ok) {
    throw new Error(`Upload failed: ${response.status}`);
  }

  return response.json();
}

Replace the example endpoint with your backend endpoint and ensure that its multipart field name matches the server's expected value. Avoid manually setting a multipart Content-Type header if the networking implementation needs to generate the boundary automatically.

12.2 Upload Validation

Before uploading, the application can check basic metadata, such as file size and the reported MIME type.

function validateDocument(document, maxSizeBytes) {
  if (!document?.uri) {
    return { valid: false, message: 'Select a document first.' };
  }

  if (
    document.size != null &&
    document.size > maxSizeBytes
  ) {
    return { valid: false, message: 'The file is too large.' };
  }

  return { valid: true, message: 'Document is ready.' };
}

Client-side checks improve usability but do not guarantee safety. The server must validate the file's actual contents, enforce size limits, check allowed formats, and apply appropriate authorization.

13. Managing Temporary and Persistent Files

Files have different lifecycles. A temporary file may only be needed during preview or upload, while a downloaded report may need to remain available to the user after the application closes.

13.1 Cache Storage

Cache storage is useful for files that can be recreated or downloaded again. The operating system may remove cache files when storage is needed, so do not treat cache storage as a permanent archive.

13.2 Document Storage

The app's document directory is appropriate for files that the application needs to retain across normal restarts. However, files stored privately in the app's container may not automatically appear in the user's public Files or Downloads interface.

13.3 Persisting a Picked Document

DocumentPicker commonly copies selected files into the application's cache when copyToCacheDirectory: true is specified. This supports immediate access by Expo FileSystem, but the cache copy is not necessarily a durable long-term copy.

const result = await DocumentPicker.getDocumentAsync({
  type: '*/*',
  copyToCacheDirectory: true,
});

if (!result.canceled) {
  const selected = result.assets[0];

  console.log('Selected URI:', selected.uri);
  console.log('Selected name:', selected.name);

  // Copy the file into application-managed storage
  // if it must remain available beyond the cache lifecycle.
}

To preserve a file, use the supported file copy or import workflow for the installed SDK and confirm that the source URI is readable. For provider-managed files, a simple path-based copy may not be sufficient in every situation.

14. Sharing and Exporting Documents

After creating or downloading a file, an application may need to let the user share it with another app or export it to a user-selected location. Sharing and exporting are distinct workflows.

  • Sharing: Opens a system share interface or sends a file to a compatible target application.
  • Exporting: Lets the user save a file to a location they choose, where the platform and available libraries support that flow.
  • Opening: Launches an appropriate viewer or application to access the file.

14.1 Example Sharing Workflow

In Expo applications, expo-sharing can share local files when the platform and file type support it.

npx expo install expo-sharing
import * as Sharing from 'expo-sharing';

async function shareDocument(fileUri) {
  try {
    const available = await Sharing.isAvailableAsync();

    if (!available) {
      console.log('Sharing is not available on this device.');
      return;
    }

    await Sharing.shareAsync(fileUri);
  } catch (error) {
    console.error('Unable to share document:', error);
  }
}

Check the current Expo Sharing documentation for platform support and limitations. A sharing interface does not guarantee that every receiving application can open every file type.

14.2 Saving to a User-Selected Location

For a genuine export workflow, use a system save dialog or an appropriate document-provider API. Avoid assuming that copying a file into the app's private document directory automatically makes it visible in the public Downloads folder.

15. Opening and Previewing Documents

File selection, file storage, and document viewing are separate responsibilities. Expo FileSystem manages file operations, while a suitable viewer or native interface is needed to display PDFs and other document formats.

15.1 Preview Workflow

  1. Let the user select or download a document.
  2. Validate that the document is available and supported.
  3. Determine the appropriate viewer for its file type.
  4. Open the document using a compatible native interface or viewer library.
  5. Display a helpful message if no compatible viewer is available.

15.2 Choosing a Document Viewer

For PDF previews or advanced document viewing, evaluate a viewer library that supports the platforms and file types your app needs. Some native viewer packages require a development build rather than Expo Go. Confirm installation and platform requirements before selecting a dependency.

16. Handling Large Files

Large files can consume memory, storage, and network bandwidth. Reading an entire file into a JavaScript string or Base64 value can be expensive and may cause performance issues.

16.1 Large File Best Practices

  • Prefer file-based operations instead of loading entire files into memory.
  • Use streaming or chunked processing where the library supports it.
  • Validate file size before upload or download.
  • Display progress and allow cancellation for long operations when supported.
  • Clean up temporary files when they are no longer needed.
  • Handle network interruptions and retry only when appropriate.
  • Avoid unnecessarily encoding files as Base64.

16.2 File Size Conversion

File sizes are commonly reported in bytes. A simple conversion can make file size easier to display.

function formatFileSize(bytes) {
  if (bytes == null || bytes < 0) {
    return 'Unknown size';
  }

  if (bytes < 1024) {
    return `${bytes} B`;
  }

  if (bytes < 1024 * 1024) {
    return `${(bytes / 1024).toFixed(1)} KB`;
  }

  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

17. File Permissions and Platform Differences

Android and iOS restrict access to device storage in different ways. Modern Android versions use scoped storage and system pickers for many file workflows. iOS uses app containers and document-provider interfaces that can grant access to selected files.

17.1 Prefer the System Document Picker

When users need to choose a document, use the system document picker instead of attempting to browse the entire filesystem. This reduces unnecessary permission requests and allows users to select files from supported providers.

17.2 Android Considerations

  • Do not assume an application can read arbitrary file paths.
  • Use supported content URIs and system document interfaces.
  • Check the current Android storage model before requesting broad storage permissions.
  • Use app-private storage for files that do not need to be publicly accessible.

17.3 iOS Considerations

  • App-private files are generally stored inside the application's sandbox.
  • Files selected through document providers may have provider-specific access behavior.
  • Cloud documents may require network access to become available.
  • Expose app documents through the Files app only when the application configuration and use case call for it.

17.4 Exposing App Documents on iOS

Expo FileSystem provides configuration options for enabling file sharing and opening documents in place where supported. These settings affect native behavior and generally require a new build.

{
  "expo": {
    "plugins": [
      [
        "expo-file-system",
        {
          "supportsOpeningDocumentsInPlace": true,
          "enableFileSharing": true
        }
      ]
    ]
  }
}

Use this configuration only when it matches the intended document workflow. Enabling public file access can change how users interact with the app's stored documents.

18. Security Best Practices for File Handling

Documents may contain personal, financial, business, or confidential information. File handling must therefore include validation, access control, safe storage, and careful error handling.

  • Validate file size and allowed file types before processing.
  • Do not trust file extensions or MIME types as proof of content.
  • Validate uploaded files on the backend as well as in the app.
  • Use HTTPS when downloading or uploading sensitive documents.
  • Authenticate and authorize access to protected backend files.
  • Avoid storing passwords, API keys, or authentication tokens in ordinary files.
  • Do not construct file paths directly from untrusted user input.
  • Use generated filenames or sanitized names to reduce path-related risks.
  • Delete temporary files when they are no longer required.
  • Do not log document contents or private URIs unnecessarily.
  • Consider encryption requirements for sensitive locally stored documents.
  • Handle malformed files safely and avoid executing downloaded content.

19. Error Handling and Troubleshooting

Problem Possible Cause Solution
Document picker returns no file User canceled the operation Check the canceled property before accessing assets.
File cannot be read immediately Picker returned a provider URI or temporary reference Use copyToCacheDirectory: true where supported and confirm file accessibility.
File does not exist Incorrect URI or file was removed Check file existence and validate the selected URI.
Download fails Network error, invalid URL, authentication failure, or HTTP error Validate the URL, handle response status, and retry appropriately.
File upload fails Incorrect multipart field, unsupported format, or backend rejection Match the API contract and inspect server validation errors.
App runs out of memory Large file loaded fully into JavaScript memory Use file-based or streaming operations where available.
File is not visible in Downloads Saved only to app-private storage Implement a user-facing export or save workflow.
File cannot be opened No compatible viewer or invalid file contents Check file validity and use a suitable viewer.
Copied file disappears later File was stored in cache Copy it to suitable persistent application storage when necessary.
File operation throws an exception Invalid path, insufficient access, or conflicting file operation Validate paths, check existence, and handle exceptions.

19.1 Use Try-Catch for File Operations

async function safeFileOperation(operation) {
  try {
    return await operation();
  } catch (error) {
    console.error('File operation failed:', error);
    return null;
  }
}

Use clear error messages and logging appropriate for development. In production, avoid exposing sensitive internal paths or raw error details to users.

20. Mini Project: Document Manager Application

20.1 Project Objective

Create a React Native application that allows users to select documents, view their metadata, save text notes, download reports, and share available files.

20.2 Functional Requirements

  1. Display a screen with document management actions.
  2. Allow users to select PDF and other supported documents.
  3. Display filename, file type, and size when available.
  4. Handle canceled selection without errors.
  5. Save a text report in app-managed storage.
  6. Read a saved text file and display its content.
  7. Download a sample report from a backend endpoint.
  8. Allow users to share supported local files.
  9. Handle unsupported formats and network errors.
  10. Validate files before uploading them to a server.

20.3 Suggested Folder Structure

FileHandlingApp/
  App.js
  components/
    DocumentPickerButton.js
    DocumentDetails.js
    FileActionButtons.js
  services/
    fileService.js
    documentUploadService.js
    downloadService.js
  utils/
    fileValidation.js
    fileSizeFormatter.js

20.4 Development Steps

  1. Create the Expo project and install the required libraries.
  2. Build a reusable document selection component.
  3. Implement file metadata display.
  4. Create file read and write functions.
  5. Implement a document download workflow.
  6. Add sharing or export functionality as required.
  7. Add file validation and error handling.
  8. Test different document formats and sizes.
  9. Test on supported Android and iOS versions.

21. Practical Exercises

  1. Create a button that opens the system document picker.
  2. Restrict document selection to PDF files.
  3. Allow users to select multiple documents and list their filenames.
  4. Display file size in bytes, KB, or MB.
  5. Create a text file in application document storage.
  6. Read the text file and display its content.
  7. Save structured data as JSON and read it back.
  8. Copy a file from a temporary location to persistent app storage.
  9. Download a sample PDF from a test endpoint.
  10. Upload a selected file to a backend using FormData.
  11. Implement a sharing workflow for a local file.
  12. Handle file access errors and canceled selection.

22. Interview Questions and Answers

Q1. What is file system integration in React Native?

It is the process of accessing and managing files and directories through platform APIs or libraries, including creating, reading, writing, downloading, copying, and deleting files.

Q2. What is Expo FileSystem?

Expo FileSystem is a library that provides APIs for managing files and directories within the application's permitted storage areas.

Q3. What is Expo DocumentPicker?

It opens the operating system's document selection interface so users can choose files from available local or cloud providers.

Q4. What is the purpose of copyToCacheDirectory?

It allows the document picker to copy the selected file into the application's cache when supported, which can make immediate file access through Expo FileSystem more reliable.

Q5. What is the difference between cache and document storage?

Cache storage is intended for temporary files that may be removed, while the app's document directory is more suitable for files that need to remain available during normal application use.

Q6. What is a file URI?

A URI identifies a file or resource location. Depending on the platform, it may be a local file URI, content URI, or provider-managed reference.

Q7. How can a document be uploaded to a backend?

A common approach is to append the file's URI, name, and MIME type to a FormData object and send it to a multipart upload endpoint.

Q8. Why should the application validate file types?

Validation helps prevent unsupported files from entering the workflow. The backend must also validate file contents because client-provided metadata can be inaccurate or manipulated.

Q9. Why might a file disappear?

The file may have been stored in a cache directory that the operating system can clear, or the original provider URI may no longer be accessible.

Q10. What is the difference between downloading and exporting?

Downloading retrieves a file from a remote source. Exporting lets a user save or share application data to a chosen destination.

Q11. Why should large files be handled carefully?

Large files can consume significant memory, storage, and bandwidth. File-based or streaming operations can help reduce memory pressure.

Q12. Can the app access every file on the device?

No. Access is restricted by the operating system, application sandbox, permission model, and user-selected document access.

Q13. How can a file be shared?

A sharing library such as Expo Sharing can open a system sharing interface for supported local files and platforms.

Q14. How should file operation errors be handled?

Use try-catch, validate the URI and file state, handle cancellation, and display a user-friendly message when an operation fails.

Q15. Why should sensitive documents be protected?

Documents may contain private information. Applications should restrict access, use secure transport, validate uploads, and avoid unnecessary local retention.

23. Quick Revision Checklist

  • Install the compatible Expo FileSystem and DocumentPicker packages.
  • Understand the difference between cache and document storage.
  • Use the document picker instead of requesting broad storage access unnecessarily.
  • Check cancellation before accessing selected document assets.
  • Inspect file metadata but do not trust it as proof of file safety.
  • Use the current FileSystem API supported by the installed SDK.
  • Handle file URIs and provider-managed documents carefully.
  • Validate downloads and uploads.
  • Keep temporary and persistent file lifecycles separate.
  • Use suitable viewer and sharing libraries when needed.
  • Handle errors and large files efficiently.
  • Protect confidential files and test on Android and iOS.

24. Conclusion

Integrating file system and document handling enables React Native applications to work with local files, user-selected documents, downloads, exports, and uploads. Expo FileSystem provides file and directory operations, while Expo DocumentPicker lets users select documents through the operating system's interface.

A reliable implementation should use appropriate storage locations, validate files, handle temporary URIs carefully, protect sensitive information, and account for differences between Android and iOS. For production applications, verify all API methods against the Expo SDK version installed in the project.

To continue learning React Native, visit the JustAcademy React Native Training Course or register for a course demo.

25. Additional Learning Resources

whatsapp